package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.json.JSONArray;

import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCursor;
import com.mongodb.util.JSON;

import mongo.UserAccount;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(description = "userManageProcess", urlPatterns = { "/manager/userManage/userManageServlet" })
public class userManageServlet extends HttpServlet{
	private UserAccount UserAccount = new UserAccount();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
		
		String method = request.getParameter("method");//需要传入method参数，判断操作
		if(method.equals("add")){ //表单提交
			this.add(request, response);
		}else if(method.equals("delete")){//传入当前数据_id
			this.delete(request, response);
		}else if(method.equals("update")){//表单提交
			this.update(request, response);
		}else if(method.equals("list")){//传入用户type
			this.list(request, response);
		}else if(method.equals("query")){//表单提交
			this.query(request, response);
		}else if(method.equals("batchAdd")){
			this.batchAdd(request, response);
		}else if(method.equals("changePwd")){//传入_id和newPwd
			this.changePwd(request, response);
		}else if(method.equals("changeOpen")){//传入_id和newOpenState
			this.changeOpen(request, response);
		}else{
//			request.getRequestDispatcher("404.jsp").forward(request, response); 添加错误页面
		}
	
	}
	
	public void changeOpen(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
        	ObjectId _id = new ObjectId(request.getParameter("_id"));
        	String type = request.getParameter("type");
        	Boolean newOpenState = Boolean.parseBoolean(request.getParameter("isopen"));
        	Boolean result = UserAccount.changeOpen(_id,newOpenState);
        	if(result) {
        		if(type.equals("t")) {
        			response.sendRedirect("updateTeachers.jsp?_id="+_id);  
        		}
        		else {
        			response.sendRedirect("updateStudents.jsp?_id="+_id);  
        		}      		     		
        	}
        	//TODO修改成功或失败跳转
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }
	}
	
	public void changePwd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
        	ObjectId _id = new ObjectId(request.getParameter("_id"));
        	String type = request.getParameter("type");
        	String newPwd = request.getParameter("newPwd");
        	Boolean result = UserAccount.changePwd(_id,newPwd);
        	if(result) {
        		if(type.equals("t")) {
        			response.sendRedirect("updateTeachers.jsp?_id="+_id);  
        		}
        		else {
        			response.sendRedirect("updateStudents.jsp?_id="+_id);  
        		}      		     		
        	}
        	//TODO修改成功或失败跳转
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }
	}
	
	public void batchAdd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
        	String fileDir = (String)request.getAttribute("fileDir");
        	String type = request.getParameter("type");
        	List<String> errresult = UserAccount.batchAdd(fileDir,type);
        	BasicDBObject queryDBobject = new BasicDBObject();
        	String returnUrl = "";
        	if(type.equals("t")){
        		queryDBobject.append("type", "t");
        		returnUrl = "teacherList.jsp";
        	}else {
        		queryDBobject.append("type", "s");
        		returnUrl = "studentList.jsp";
        	}
        	MongoCursor<Document> result = UserAccount.query(queryDBobject);
        	request.setAttribute("result", result);
        	request.setAttribute("errresult", errresult);
        	request.getRequestDispatcher(returnUrl).forward(request, response);
        	//TODO根据添加的童虎类型返回相应的list
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }
	}
	
	public void add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
        	Document newDocument = new Document();
        	Enumeration<String> names = request.getParameterNames();
        	while(names.hasMoreElements()){
        		String name = names.nextElement();
        		if(name.equals("departmentid") || name.equals("majorid") || name.equals("classid")){
            		ObjectId value = new ObjectId(request.getParameter(name));
                	newDocument.append(name, value);
        		}
        		else {
        			String value = request.getParameter(name);
        			if(value==null){
        				newDocument.append(name, "无");
        			}else{
        				newDocument.append(name, value);
        			}  
        		}
        	}
        	Boolean result = UserAccount.add(newDocument);
        	if(result) {
    			this.list(request, response);
    		}
        	//TODO得到查询结果，跳转到结果显示页面
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }
	}
	
	
	public void delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
    		ObjectId _id = new ObjectId(request.getParameter("_id"));
    		Boolean result = UserAccount.delete(_id);
    		if(result) {
    			this.list(request, response);
    		}
        	//TODO删除成功
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }
	}
	
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
        	String type = request.getParameter("type");
        	BasicDBObject queryDBobject = new BasicDBObject("type",type);
        	MongoCursor<Document> result = UserAccount.query(queryDBobject);
        	request.setAttribute("result", result);
        	if(type.equals("t")){
        		request.getRequestDispatcher("teacherList.jsp").forward(request, response);
        	}
        	else {
        		request.getRequestDispatcher("studentList.jsp").forward(request, response);
        	}
        	//TODO得到查询结果，跳转到结果显示页面
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }
	}
	
	
	public void query(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String type = request.getParameter("type");
		String queryname = request.getParameter("name");
    	String queryvalue = request.getParameter("value");
    	if(queryvalue.equals("")) {
    		this.list(request, response);
    	}
    	else {
    		BasicDBObject queryDBobject = new BasicDBObject(queryname,queryvalue).append("type", type);
        	MongoCursor<Document> result = UserAccount.query(queryDBobject);
        	request.setAttribute("queryname", queryname);
        	request.setAttribute("queryvalue", queryvalue);
        	request.setAttribute("result", result);
        	if(type.equals("t")){
        		request.getRequestDispatcher("teacherList.jsp").forward(request, response);
        	}
        	else {
        		request.getRequestDispatcher("studentList.jsp").forward(request, response);
        	}
    	}
	}
	
	public void update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
        	ObjectId _id = new ObjectId(request.getParameter("_id"));
        	Document updateDocument = new Document();
        	Enumeration<String> names = request.getParameterNames();
        	while(names.hasMoreElements()){
        		String name = names.nextElement();
        		if(!name.equals("_id")) {
        			if(name.equals("departmentid") || name.equals("majorid") || name.equals("classid")){
            			ObjectId value = new ObjectId(request.getParameter(name));
            			updateDocument.append(name, value);
            		}
        			else {
        				String value = request.getParameter(name);
                		updateDocument.append(name, value);
        			}
        		}
        	}
    		Boolean result = UserAccount.update(_id, updateDocument);
    		if(result) {
    			this.list(request, response);
    		}
        	//TODO得到结果，跳转到显示页面，如果更新的用户是使用者，则更新session
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }
	}
	
	
	
}
